package com.kakavr.staff.controller;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.collect.Maps;
import com.kakavr.auth.util.EncryptionUtils;
import com.kakavr.base.controller.BaseController;
import com.kakavr.base.exception.ValidateParamException;
import com.kakavr.result.MsgResult;
import com.kakavr.result.constant.MsgConstants;
import com.kakavr.staff.service.IStaffLoginService;
import com.kakavr.util.SessionUtils;
/**
 * 平台登录
 * @author gang.yang
 *
 */
@RestController
@RequestMapping("/n/login")
public class StaffLoginController extends BaseController {
	@Resource
	private IStaffLoginService staffLoginService;
	
	@RequestMapping(value = "signIn", method = RequestMethod.POST)
	public Map<String, Object> signIn(HttpServletRequest request){
		String userName = request.getParameter("name");
		String password = request.getParameter("password");
		if(StringUtils.isBlank(userName)){
			throw new ValidateParamException(MsgConstants.MSG_CODE_1001, MsgConstants.MSG_CONTENT_1001,"用户名");
		}
		if(StringUtils.isBlank(password)){
			throw new ValidateParamException(MsgConstants.MSG_CODE_1001, MsgConstants.MSG_CONTENT_1001,"密码");
		}
		Map<String,Object> map = Maps.newHashMap();
		map.put("username", userName);
		Map<String,Object> user = staffLoginService.selectStaffInfo(map);
		if(null == user || user.isEmpty()){
			throw new ValidateParamException(MsgConstants.MSG_CODE_1002, MsgConstants.MSG_CONTENT_1002,"用户名密码");
		}
		int status = (int) user.get("status");
		if(status < 1){
			throw new ValidateParamException(MsgConstants.MSG_CODE_2002, MsgConstants.MSG_CONTENT_2002);
		}
		Object pass = user.get("password");
		if(password.equals(pass) || EncryptionUtils.md5(password).equals(pass)){
			SessionUtils.setCurUser(user);
			map.clear();
			map.put("name", user.get("name"));
			map.put("userName", user.get("userName"));
			map.put("mobile", user.get("mobile"));
			map.put("roleId", user.get("roleId"));
			map.put("role", user.get("role"));
			map.put("isPartner", user.get("isPartner"));
			return MsgResult.okResultData(map);
		}
		throw new ValidateParamException(MsgConstants.MSG_CODE_1002, MsgConstants.MSG_CONTENT_1002,"用户名密码");
	}
	
	/**
	 * 退出登录
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "logon", method = RequestMethod.GET)
	public Map<String, Object> logon(HttpServletRequest request){
		HttpSession session = SessionUtils.getSession();
		if (null != session) {
			session.invalidate();
		}
		return MsgResult.okResult();
	}
}
